﻿using System;
using System.Collections.Generic;
using UnityEngine;

public class Turn : MonoBehaviour
{
    [SerializeField] public float Rotation;
    [SerializeField] public float Torque;
    private List<Player> m_Players = new List<Player>();

    public ColliderTrigger playerTrigger;

    public Transform from;
    public Transform to;

    private void Start()
    {
        if (playerTrigger == null) playerTrigger = GetComponentInChildren<ColliderTrigger>();
        playerTrigger.onTriggerEnter = DoOnTriggerEnter;
        playerTrigger.onTriggerExit = DoOnTriggerExit;
    }

    private void DoOnTriggerEnter(ColliderTrigger arg1, Collider other)
    {
        var player = other.gameObject.GetComponent<Player>();

        if (player)
        {
            m_Players.Add(player);
        }
    }
    private void DoOnTriggerExit(ColliderTrigger arg1, Collider other)
    {
        var player = other.gameObject.GetComponent<Player>();
        if (player && m_Players.Contains(player))
        {
            Vector3 dir = (to.position - @from.position).normalized;
            
            float dot = Vector3.Dot(dir, player.transform.forward);
            float angle = Mathf.Acos(dot) * Mathf.Rad2Deg;
            if (angle < 60)
            {
                player.AdjustDir(dir);
            }
            
            GameDebug.LogError($"player exit :{other.name}");
            /*if (Mathf.Abs(dir.z) > Mathf.Abs(dir.x))
            {
                if(dir.z > 0)
                    player.transform.localRotation = Quaternion.Euler(0,0,0);
            }
            else
            {
                if(dir.x > 0)
                    player.transform.localRotation = Quaternion.Euler(0,90,0);
                else
                    player.transform.localRotation = Quaternion.Euler(0,-90,0);
            }*/
            m_Players.Remove(player);
        }
    }


    private void OnTriggerEnter(Collider other)
    {
    }

    private void OnTriggerExit(Collider other)
    {
        
    }

    private void Update()
    {
        foreach (var player in m_Players)
        {
            if (player.curAction.stateId == MActionStateType.run)
            {
                //player.Rigidbody.angularVelocity = Torque * new Vector3(0,Rotation,0);
                player.transform.Rotate(Vector3.up,Time.deltaTime * Torque * Rotation);
            }
        }
        
    }
}
